<?php
namespace Admins\Model;
use Think\Model;
class DataokeApiModel extends Model {
	protected $tableName = 'dataoke_product';

	protected $_validate = array(
		//array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
/*		array('email','require','email没有填写'),
		array('email','email','邮箱格式不对！'),
		array('email','','帐号名称已经存在！',0,'unique',1),
		array('password','require','密码不能为空！'), 
		array('password','password2','确认密码不正确',0,'confirm'),
		array('verify','require','验证码不能为空！'), 
		array('verify','ChVerifyCode','验证码不正确！',1,'callback'),*/
	);

	
	public function onlyCheck($GoodsID)
	{//检查数据库字段的唯一性
		$sql = "select ID from ".C('DB_PREFIX')."dataoke_product where GoodsID = '".$GoodsID."'";
		$data = $this->query($sql);	
		//$data = $this->execute($sql);	
		if($data)
		{
			return true;
		}
		else
		{
			return false;
		}
		
	
	}
	public function quanOnlyCheck($GoodsID,$quanID)
	{//券信息是否唯一
		$sql = "select ID from ".C('DB_PREFIX')."dataoke_product where GoodsID = '".$GoodsID."' and Quan_id = '".$quanID."'";
		$data = $this->query($sql);	
		//$data = $this->execute($sql);	
		if($data)
		{
			return true;
		}
		else
		{
			return false;
		}	
	}
	public function getlist()
	{
		$map = array();//查询条件
		//import('ORG.Util.Page');// 导入分页类
		
		$count      = $this->where($map)->count();// 查询满足要求的总记录数
		//$Page       = new \Think\Page($count,25);
		$Page       = new \Common\Util\DiyPage($count,25);// 实例化分页类 传入总记录数和每页显示的记录数
		
		$now = "共：%TOTAL_ROW%条数据 / 共%TOTAL_PAGE%页";
		$total = "%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%";
		$page = "";
		$str = $now." ".$total." ".$page;
		$Page->setConfig('theme',$str);		
		
		
		//分页跳转的时候保证查询条件
		foreach($map as $key=>$val) {
			$Page->parameter   .=   "$key=".urlencode($val).'&';
		}

		$page       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $this->where($map)->order('Ctime')->limit($Page->firstRow.','.$Page->listRows)->select();
		$result['list'] = $list ;
		$result['page'] = $page; 
		return $result;
	}
	public function oneInsert()
	{
	}
	public function oneUpdate()
	{
	}
	public function moreInsert()
	{
	}
	public function moreUpdate()
	{
	}
	public function moreExecute($arrSql)
	{//数组形式接受sql语句
		$sql = $arrSql[0];
		$data = $this->execute($sql);	
		if($data)
		{
			return true;
		}
		else
		{
			return false;
		}		
		
	
	}
	public function getInsertSql($data)
	{//只返回sql语句,不执行
		
		$sql = $this->fetchSql(true)->add($data);
		return $sql;	
	}
	public function getUpdateSql($data)
	{
		//$field = array('Title','D_title','Pic','Price','Quan_id','Quan_price','Quan_time','Quan_m_link','Quan_link','Ctime');
		$sql = $this->fetchSql(true)->save($data);
		return $sql;		
	}
	

	public function insertData($page='1')
	{//复制控制器中的call()
		
		$DataokePages = $this->getPages();
		$listData = $this->getData($page);
		$data = '';
//新定义一个录入数据库的数组
		foreach($listData as $k=>$v)
		{
			$product['ID'] = $v['ID'];
			$product['GoodsID'] = $v['GoodsID'];
			$product['Title'] = $v['Title'];
			$product['D_title'] = $v['D_title'];
			$product['Pic'] = $v['Pic'];
			$product['Cid'] = $v['Cid'];
			$product['Org_Price'] = $v['Org_Price'];
			$product['Price'] = $v['Price'];
			$product['IsTmall'] = $v['IsTmall'];
			$product['Sales_num'] = $v['Sales_num'];
			$product['Dsr'] = $v['Dsr'];
			$product['SellerID'] = $v['SellerID'];
			$product['Commission'] = $v['Commission'];
			$product['Commission_jihua'] = $v['Commission_jihua'];
			$product['Commission_queqiao'] = $v['Commission_queqiao'];
			$product['Jihua_link'] = $v['Jihua_link'];
			$product['Que_siteid'] = $v['Que_siteid'];
			$product['Jihua_shenhe'] = $v['Jihua_shenhe'];
			$product['Introduce'] = $v['Introduce'];
			$product['Quan_id'] = $v['Quan_id'];
			$product['Quan_price'] = $v['Quan_price'];
			$product['Quan_time'] = $v['Quan_time'];
			$product['Quan_surplus'] = $v['Quan_surplus'];
			$product['Quan_receive'] = $v['ID'];
			$product['Quan_condition'] = $v['Quan_condition'];
			$product['Quan_m_link'] = $v['Quan_m_link'];
			$product['Quan_link'] = $v['Quan_link'];
			$product['Ctime'] = date('Y-m-d H:i:s');
			
			$data[$k] = $product;
		}

//------------------------------
		$sql = '';	
		foreach($data as $v)
		{

			$isNewdata = $this->onlyCheck($v['GoodsID']);
			if($isNewdata)
			{//更新操作语句
				//接下来如果券一样的话不进行任何操作，券不一样了再更新
				if(!($this->quanOnlyCheck($v['GoodsID'],$v['Quan_id'])))
				{
					$sql .= $this->getUpdateSql($v).';';
				}
			}
			else
			{//插入操作语句
				
				$sql .= $this->getInsertSql($v).';';
				
				
			}		
		}
		//echo $sql;
		if($sql == '')
		{
			return false;
		}
		//定义一个数组，把这些sql语句以一个引用（指针）传过去，不然直接把字符串当参数太大，太消耗内存了。
		$arraySql[] = $sql;
		//echo $arraySql;
		$result = $this->moreExecute($arraySql);
		return $result;
	
	
	}
	public function getPages()
	{//获取大淘客总页数，作为循环次数
	
		//这里要写如果获取数据错误的处理，暂时未写
		$getJson = file_get_contents($this->getDataokeUrl());
		$data = json_decode($getJson,TRUE);
		$head_data = $data['data'];
		$total_num = $head_data['total_num'];
		return  ceil($total_num/200);	
	}
	public function getData($page=1)
	{
		//这里要写如果获取数据错误的处理，暂时未写
		$opts = array(   
			  'http'=>array(   
				'method'=>"GET",   
				'timeout'=>5,//单位秒  
			   )   
			);  
		$cnt=0;   
//		while($cnt<5 && ($getJson=file_get_contents($this->getDataokeUrl($page), false, stream_context_create($opts)))===FALSE) 
//		{$cnt++; 
//		echo "执行$cnt次"; 
//		flush();
//		} 

	//echo $this->getDataokeUrl($page);
		while($cnt<5 && ($getJson=file_get_contents($this->getDataokeUrl($page), false, stream_context_create($opts)))===FALSE) $cnt++; 
			
		//var_dump($getJson);
		if($getJson)
		{//正确获取到数据
			$data = json_decode($getJson,TRUE);	
			$result = $data['result'];
		}
		else
		{//错误未获取到数据
			$result = "";
		}

		//var_dump($result);
		return $result;
		
	}
	public function getDataokeUrl($page = 1)
	{//同过方法处理大淘客的Url
		$dataokeUrl = "http://api.dataoke.com/index.php?r=Port/index&type=total&appkey=motzfcyc8h&v=2&page=".$page;
		//echo $dataokeUrl;
		return $dataokeUrl;
	}
	public function getOneData($goodsId)
	{//获取一条记录,暂时只获取券id,佣金计划之后又需求在扩展
		$sql = "select id,GoodsID,Quan_id,Commission,Commission_jihua,Commission_queqiao from ".C('DB_PREFIX')."dataoke_product where goodsId = '".$goodsId."'";
		$data = $this->query($sql);	
		//$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	public function getZhoushouInsertSql($data)
	{//先没用
		$sql = " INSERT INTO ".C('DB_PREFIX')."zhoushou_api (GoodsID,Title,taokeShortUrl,promoterType,time) 
		VALUES('".$data['goodsid']."','".$data['title']."','".$data['ali_click']."','".$data['promotertype']."','".$data['time']."');";
		return $sql;
	
	}
	public function onlyCheckZhoushouApi($goodsId,$groupId)
	{//读取缓存表数据
		$sql = "select id from ".C('DB_PREFIX')."promoter_dataoke_product where goodsId = '".$goodsId."' and groupId = '".$groupId."'";
		$data = $this->query($sql);	
		//$data = $this->execute($sql);	
		if($data)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public function getTimeProduct()
	{//查询出要删除的数据
		$sql =  "select ID,GoodsID FROM ".C('DB_PREFIX')."dataoke_product where Ctime < '".date("Y-m-d H:i:s",strtotime("-2 day"))."' Limit 0,50";
		$data = $this->query($sql);	
		//$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}
		
	}
	public function getTimeProductNum()
	{//查询出要删除的数据
		$sql =  "select ID FROM ".C('DB_PREFIX')."dataoke_product where Ctime < '".date("Y-m-d H:i:s",strtotime("-2 day"))."'";
		//$data = $this->query($sql);	
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}
		
	}
	public function delTimeProduct($DelId)
	{//查询出要删除的数据

		$result = $this->delete($DelId);
		if($result)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	public function delTimeProduct_bak()
	{//以时间为条件删除数据，上传2天前的数据
	//这样有个缺点 如果数据量大了 估计服务器着不住---先查询再批量删除
		$sql =  "delete FROM ".C('DB_PREFIX')."dataoke_product where Ctime < '".date("Y-m-d H:i:s",strtotime("-2 day"))."'";
		
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	public function getNoquanProduc()
	{//无券检测-查找30-50个数据
		$sql =  "select ID,GoodsID,Quan_id,SellerID FROM ".C('DB_PREFIX')."dataoke_product where IsQunNull=0 Limit 0,20";
		$data = $this->query($sql);	
		//$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	public function getNoquanProductNum()
	{//无券检测-查找数据总数
		$sql =  "select ID FROM ".C('DB_PREFIX')."dataoke_product where IsQunNull=0";
		//$data = $this->query($sql);	
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	public function updateNoquanProduct($id,$value)
	{//无券检测-更新操作--仅仅把IsQunNull字段更新为非零(1表示无券了)
		$sql = "UPDATE ".C('DB_PREFIX')."dataoke_product SET `IsQunNull` = $value where `ID`=".$id;
		//$data = $this->query($sql);	
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	public function updateInitNoquanProduct()
	{//无券检测-更新操作--重新初始化 把改成2个IsQunNull的有券产品重新改成0，方便下一次遍历检测
		$sql = "UPDATE ".C('DB_PREFIX')."dataoke_product SET `IsQunNull` = 0 where `IsQunNull`<>1 ";
		//$data = $this->query($sql);	
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	public function delNoquanProduct()
	{//无券检测-删除操作
		$sql =  "delete FROM ".C('DB_PREFIX')."dataoke_product where IsQunNull=1";
		
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}		
	}
	public function getNullQunproductNum()
	{//获取无券数据总数
		$sql =  "select ID FROM ".C('DB_PREFIX')."dataoke_product where IsQunNull=1";
		//$data = $this->query($sql);	
		$data = $this->execute($sql);	
		if($data)
		{
			return $data;
		}
		else
		{
			return false;
		}	
	}
	
}
?>